<?php

// $Id$

require_once($PATHS->get_hidden().'inc/modules/visitors_cookies/visitor_cookie_dbc.class.php');


class Visitor_Cookie_Handler extends Tangra_Class {
	public static function handle_cookie(Visitor_Cookie_DBC $cookie, DB_Connection $dbc, Web_Context $context, $vc_config) {
		if ($context->exists_in_cookie($vc_config['cookie_name'])) {
			$cookie_id = Visitor_Cookie_Handler::check_cookie($dbc, $context->get_from_cookie($vc_config['cookie_name']));
			if ($cookie_id) {
				$cookie->load_by_id($dbc, $cookie_id);

				//updating expire date
				setcookie($vc_config['cookie_name'],
							$cookie->get_cookie(),
							$vc_config['expire'] * 60*60*24 + time(),
							$vc_config['path']
							);
			} else {
				$cookie = Visitor_Cookie_Handler::create_cookie($cookie, $dbc, $vc_config);
			}
		} else {
			$cookie = Visitor_Cookie_Handler::create_cookie($cookie, $dbc, $vc_config);
		}

		return $cookie;
	}


	private static function check_cookie(DB_Connection $dbc, $cookie) {
		$ret = false;

		$tmp = Visitor_Cookie_DBC::cookie_exists($dbc, $cookie);
		if ($tmp) {
			$ret = $tmp;
		}

		return $ret;
	}


	private static function create_cookie(Visitor_Cookie_DBC $cookie, DB_Connection $dbc, $vc_config) {
		$cookie->set_cookie(Visitor_Cookie_DBC::generate_new_cookie($dbc));
		$cookie->set_new(true);
		setcookie($vc_config['cookie_name'],
					$cookie->get_cookie(),
					$vc_config['expire'] * 60*60*24 + time(),
					$vc_config['path']
					);

		$cookie->save($dbc);

		return $cookie;
	}
}